if exists (SELECT * from dbo.sysobjects WHERE id = object_id(N'[dbo].[vw_purchases_orders_labeled_distributed_amounts]') AND OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[vw_purchases_orders_labeled_distributed_amounts]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/***********************************************************************
* vw Name: dbo.vw_purchases_orders_labeled_distributed_amounts
* Created: 20101130, RGM
* Purpose: listado de los montos distribuidos de las po en el periodo
*	actual y el total de lo distribuido previamente
*
* Modified: yyyymmdd, user, data
*
* HistoryDate.
*	yyyymmdd, user, data
* 
* Note: nothing
* 
***********************************************************************/
CREATE VIEW dbo.vw_purchases_orders_labeled_distributed_amounts AS
SELECT DISTINCT pov.purchase_order_version_id, pv.plant_version_id, pvo.plant_version_id old_plant_version_id, 
		ISNULL(md.quantity, 0) distributed_qty, 
		ISNULL(mdo.quantity, 0) old_distributed_qty
	FROM purchases_orders_versions pov
		CROSS JOIN plants_versions pv
		LEFT OUTER JOIN plants_versions pvo
			ON pv.plant_version_id > pvo.plant_version_id
			AND pv.plant_id = pvo.plant_id
		LEFT OUTER JOIN monthly_distributions_per_plants_details mdo
			ON pov.purchase_order_version_id = mdo.purchase_order_version_id
			AND pvo.plant_version_id = mdo.plant_version_id
			AND mdo.labeled = 1
		LEFT OUTER JOIN monthly_distributions_per_plants_details md
			ON pov.purchase_order_version_id = md.purchase_order_version_id
			AND pv.plant_version_id = md.plant_version_id
			AND md.labeled = 1
